package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.ServiceIml;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //设置请求编码
            request.setCharacterEncoding("utf-8");

            //获取用户输入验证码
            String verifycode = request.getParameter("verifycode");

            //获取Session中验证码
            HttpSession session = request.getSession();
            String checkcode_server =(String) session.getAttribute("CHECKCODE_SERVER");

            //确保验证码的一次性
            session.removeAttribute(checkcode_server);

            //判断验证码是否一致
            if(!verifycode.equalsIgnoreCase(checkcode_server)){
                //不一致
                request.setAttribute("msg","验证码有误");
                //转发到login.jsp
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return;
            }
            //校验用户名和密码

            //获取用户所有的参数信息
            Map<String, String[]> parameterMap = request.getParameterMap();

            //将信息封装到User对象中
            User user = new User();
            BeanUtils.populate(user,parameterMap);

            //调用Service中login方法
            UserService service=new ServiceIml();
            User user1= service.login(user);

            //判断user1是否为空
            if(user1==null){
                //用户名或密码错误
                //将信息保存到request域中
                request.setAttribute("msg","用户名或密码错误");
                //转发到login.jsp
                request.getRequestDispatcher("/login.jsp").forward(request,response);

                return;
            }

            //用户名密码正确
            //保存信息到Session域中
            session.setAttribute("user",user1);
            //重定向到index.jsp
            response.sendRedirect(request.getContextPath()+"/index.jsp");

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
